#!/usr/bin/python

if __name__ == '__main__':
    import os

import string
import sys
import subprocess

GIT = 'git'
DOWNLOAD_CONFIG = '/backup/opensource-code/python_src/download/download.txt'
WORK_DIR = 'work_dir'

class Component(object):
    split_symbol = '='

    def __init__(self, context):
        self.__context = context

    def parser(self):
        if ''!=self.__context:
            split_pos = string.find(self.__context, self.__class__.split_symbol)
            if -1!=split_pos:
                result = string.split(self.__context, self.__class__.split_symbol)
                self.__component = result[0]
                self.__server = string.replace(result[1], '\n', '')
                return True
            else:
                return False
        else:
            return False
    
    def get_target(self):
        return self.__component
    def get_command(self):
        return self.__server

class CoreID(object):
    def __init__(self, coreID):
        self.__coreID = coreID
    def get_coreID(self):
        return self.__coreID

class Download(object):
    def __init__(self, download_file):
        self.__download_file__ = download_file;
        self.__component = {}
        
    def download(self, component, coreID):
        self.__coreID = coreID
        dir_prefix = ''
        component_path = ''
        if True==self.__get_component( self.__download_file__ ):
            dir_prefix = self.__component[WORK_DIR]
            for each_component in self.__component:
                if WORK_DIR==each_component:
                    dir_prefix = self.__component[each_component]
                else:
                    if ''==dir_prefix:
                        component_path = './%s' %each_component
                    else:
                        if 'all'==component[0] or each_component==component[0]:
                            component_path = '%s/%s' %(dir_prefix, each_component)
                            print '==============================================='
                            print '======== Begin download %s ==========' %each_component
                            print '==============================================='
                            if True==self.__download_core( component_path, self.__coreID.get_coreID(), 
                                    self.__component[each_component] ):
                                print '==============================================='
                                print '======== download %s done==========' %each_component
                                print '==============================================='
                                continue
                            else:
                                return False
            return True
        else:
            return False
    
    def support(self):
        if True==self.__get_component( self.__download_file__ ):
            print 'You can download :'
            for each_component in self.__component:
                if WORK_DIR!=each_component:
                    print '  \'%s\'' %each_component
            print '  \'all\' to download all'
    
    def __download_core( self, component, coreID, command ):
        if False==os.path.exists( component ):
            try:
                os.mkdir( component )
            except OSError, e:
                print >>sys.stderr, 'fatal: cannot make %s directory: %s' \
                        %( component, e.strerror )
                return False
        init_command = [GIT, 'init']
        download_command = [GIT, 'pull']
        server = '%s@%s' %(coreID, command)
        split_server = string.split(server)
        download_command += split_server
        #print 'download : ', download_command
        try:
            subprocess.Popen(init_command, cwd=component).wait()
            subprocess.Popen(download_command, cwd=component).wait()
        except OSError, e:
            print >>sys.stderr, 'fatal: download %s failed' %component
            return False

        return True

    def __get_component( self, file ):
        if False==os.path.exists(file):
            print 'fatal: file %s is not exists' %file
            return False

        f = open( file, 'r' )
        context = f.readlines()
        f.close()
        for eachline in context:
            #print 'This line : ', eachline
            p = Component( eachline )
            if True==p.parser():
                    self.__component[p.get_target()] = p.get_command()
            else:
                return False
            del p

        return True

if __name__ == '__main__':
    download = Download(DOWNLOAD_CONFIG)
    if 0!=len(sys.argv[1:]):
        if '-h'==sys.argv[1:][0]:
            download.support()
        else:
            core = raw_input("Plesae Input your CoreID: ")
            if ''!=core:
                ID = CoreID( core )
                download.download( sys.argv[1:], ID )
            else:
                print 'Core ID cannot be None!'
    else:
        download.support()

